package com.ly.blog_common.utils;

import com.alibaba.fastjson.JSONObject;
import com.github.jarod.qqwry.IPZone;
import com.github.jarod.qqwry.QQWry;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;

/**
 * 地址分析工具
 *
 * @author ly
 * create at 2021/8/25 - 14:26
 **/
@Slf4j
public class AddrUtils {


    /**
     * 通过请求IP获取
     */
    //根据IP地址解析城市
    public static String getCityByIp(HttpServletRequest request) {
        return getCityByIp(IPUtils.getIpAddr(request));
    }

    //根据IP地址解析城市
    public static String getAllAddrByIp(String ip) {
        String allAddr = "未知";
        QQWry wry = null;
        try {
            wry = new QQWry();
            IPZone zone = wry.findIP(ip);
            allAddr = zone.getMainInfo() +"_"+ zone.getSubInfo();
        } catch (Exception e) {
            log.info("获取IP城市-运营商异常======"+e.getMessage());
        }
        return allAddr;
    }
    //根据IP地址解析城市
    public static String getCityByIp(String ip) {
        String cityName = "未知";
        QQWry wry = null;
        try {
            wry = new QQWry();
            IPZone zone = wry.findIP(ip);
            cityName = zone.getMainInfo();
        } catch (Exception e) {
            log.info("获取IP城市异常======"+e.getMessage());
        }
        return cityName;
    }

    //网络所属运营商 -- 电信 联通 长城
    public static String getProviderByIp(String ip) {
        String provideName = "未知";
        QQWry wry = null;
        try {
            wry = new QQWry();
            IPZone zone = wry.findIP(ip);
            provideName = zone.getSubInfo();
        } catch (Exception e) {
            log.info("获取IP运营商异常======"+e.getMessage());
        }
        return provideName;
    }



    /**
     * 通过获取Header中的地址信息
     */
    public static final String LNG = "lng";
    public static final String LAT = "lat";
    public static final String ADDRESS_DETAIL = "addressDetail";
    public static JSONObject getCurrentPositionFromHeader(HttpServletRequest request){
        final String CURRENT_POSITION_HEADER = "currentPosition";
        String currentPosition = request.getHeader(CURRENT_POSITION_HEADER);
        if(StringUtils.isBlank(currentPosition)){
            return null;
        }
//        {"lng":121.18112,"lat":37.56352,"addressDetail":"山东省-烟台市-福山区-古现街道-长江路-302号（山东省烟台市福山区古现街道人才公寓业达科技园）"}
        currentPosition = StringUtils.unescape(currentPosition);
        JSONObject json = JSONObject.parseObject(currentPosition);
        return json;
    }



}
